<template>
  <view class="edit-profile-container">
    <view class="header">
      <view class="title">编辑资料</view>
    </view>
    
    <view class="form-container">
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          v-model="form.nickName" 
          class="form-input" 
          type="text" 
          placeholder="请输入昵称"
          :class="{'error': errors.nickName}"
          @input="clearError('nickName')"
          maxlength="255"
        />
      </view>
      <text v-if="errors.nickName" class="error-text">{{ errors.nickName }}</text>

      <view class="form-item">
        <text class="form-label">性别</text>
        <view class="gender-selector">
          <view 
            class="gender-item" 
            :class="{'active': form.gender === 1}"
            @tap="selectGender(1)"
          >
            <text>男</text>
          </view>
          <view 
            class="gender-item" 
            :class="{'active': form.gender === 2}"
            @tap="selectGender(2)"
          >
            <text>女</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">邮箱</text>
        <input 
          v-model="form.email" 
          class="form-input" 
          type="text" 
          placeholder="请输入邮箱"
          :class="{'error': errors.email}"
          @input="clearError('email')"
          maxlength="128"
        />
      </view>
      <text v-if="errors.email" class="error-text">{{ errors.email }}</text>

      <view class="form-item">
        <text class="form-label">地址</text>
        <input 
          v-model="form.address" 
          class="form-input" 
          type="text" 
          placeholder="请输入地址"
          :class="{'error': errors.address}"
          @input="clearError('address')"
          maxlength="255"
        />
      </view>
      <text v-if="errors.address" class="error-text">{{ errors.address }}</text>

    </view>
    
    <button 
      class="save-btn" 
      :disabled="loading"
      @tap="handleSave"
    >
      <text v-if="!loading">保存</text>
      <view v-else class="loading-container">
        <view class="loading-spinner"></view>
        <text>保存中...</text>
      </view>
    </button>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { getUserInfo, updateUserInfo } from '@/api'

const form = reactive({
  nickName: '',
  gender: 0,
  email: '',
  address: ''
})

const errors = reactive({
  nickName: '',
  email: '',
  address: ''
})

const loading = ref(false)
const userId = ref(null)

// 验证邮箱格式
const validateEmail = (email) => {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return regex.test(email)
}

// 表单验证
const validateForm = () => {
  let isValid = true
  errors.nickName = ''
  errors.email = ''
  errors.address = ''

  if (form.nickName && form.nickName.length > 255) {
    errors.nickName = '昵称过长'
    isValid = false
  }

  if (form.email && !validateEmail(form.email)) {
    errors.email = '请输入正确的邮箱格式'
    isValid = false
  } else if (form.email && form.email.length > 128) {
    errors.email = '邮箱过长'
    isValid = false
  }

  if (form.address && form.address.length > 255) {
    errors.address = '地址过长'
    isValid = false
  }

  return isValid
}

// 清除错误
const clearError = (field) => {
  errors[field] = ''
}

// 选择性别
const selectGender = (gender) => {
  form.gender = gender
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const userInfo = await getUserInfo()
    // 使用profile中的userId作为用户ID
    userId.value = userInfo.profile?.userId || userInfo.id
    // 从profile对象中获取用户资料信息
    const profile = userInfo.profile || {}
    form.nickName = profile.nickName || ''
    form.gender = profile.gender ?? 0  // 使用空值合并运算符，因为gender可能为null
    form.email = profile.email || ''
    form.address = profile.address || ''
  } catch (error) {
    console.error('获取用户信息失败:', error)
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
  }
}

// 保存资料
const handleSave = async () => {
  if (!validateForm()) return

  loading.value = true

  try {
    await updateUserInfo(userId.value, {
      nickName: form.nickName,
      gender: form.gender,
      email: form.email,
      address: form.address
    })

    // 更新本地存储的用户信息
    const localUserInfo = uni.getStorageSync('userInfo') || {}
    const updatedUserInfo = {
      ...localUserInfo,
      nickName: form.nickName,
      gender: form.gender,
      email: form.email,
      address: form.address
    }
    uni.setStorageSync('userInfo', updatedUserInfo)

    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    })

    // 延迟返回上一页并刷新
    setTimeout(() => {
      // 返回上一页并触发刷新
      uni.navigateBack({
        success: () => {
          // 通过事件总线通知上一页刷新
          uni.$emit('refreshUserInfo')
        }
      })
    }, 1000)

  } catch (error) {
    console.error('保存失败:', error)
    // 错误信息已由API自动处理
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
.edit-profile-container {
  min-height: 100vh;
  background: #f8f8f8;
}

.header {
  text-align: center;
  padding: 40rpx 0;
  background: #fff;
  
  .title {
    font-size: 36rpx;
    font-weight: 600;
    color: #2c2c2c;
  }
}

.form-container {
  width: 690rpx;
  margin: 50rpx auto;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 10rpx;
  box-shadow: 0 0 30rpx rgba(0,0,0,0.05);
}

.form-item {
  padding: 0 30rpx;
  min-height: 100rpx;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  
  &:last-child {
    border-bottom: 0;
  }
}

.form-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #2c2c2c;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 60rpx;
  padding: 0 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  margin-left: 20rpx;
  
  &.error {
    border-color: #ff4757;
  }
  
  &:focus {
    border-color: #667eea;
  }
}

.gender-selector {
  flex: 1;
  display: flex;
  gap: 20rpx;
  margin-left: 20rpx;
}

.gender-item {
  flex: 1;
  height: 60rpx;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #666;
  
  &.active {
    background: #667eea;
    border-color: #667eea;
    color: #fff;
  }
}

.error-text {
  color: #ff4757;
  font-size: 22rpx;
  margin-top: 10rpx;
  margin-left: 160rpx;
  display: block;
}

.save-btn {
  width: 690rpx;
  height: 80rpx;
  background: #667eea;
  border: none;
  border-radius: 8rpx;
  color: #fff;
  font-size: 28rpx;
  margin: 50rpx auto;
  line-height: 80rpx;
  
  &:active {
    background: #5a6fd8;
  }
  
  &:disabled {
    opacity: 0.6;
  }
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 30rpx;
  height: 30rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s linear infinite;
  margin-right: 16rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style> 